package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IShopService iShopService;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        String key =CACHE_SHOP_KEY + id;
        // 解决缓存击穿
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        Shop shop = queryWithPassThrough(id);
        // 互斥锁解决缓存击穿
//        Shop shop = queryWithMutex(id);
//        // // 逻辑过期解决缓存击穿
//        Shop shop = queryWithLogicalExpire(id);
        cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY,id, Shop.class,this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        // 7.返回
        return Result.ok(shop);
    }


//    // 互斥锁方法解决缓存击穿
//    public Shop queryWithMutex(Long id){
//        String key =CACHE_SHOP_KEY + id;
////        1.从redis中查找缓存
//        String shopid = stringRedisTemplate.opsForValue().get(key);
//
//        // 2.判断是否存在
//        if (StrUtil.isNotBlank(shopid)){
//            //3.存在则返回
//            Shop shop = JSONUtil.toBean(shopid, Shop.class);
//            return shop;
//        }
//
//        //判断命中的是否是空值
//        if (shopid!= null){
//            return null;
//        }
//
//        //4.不存在，实现缓存重建
//        //4.1 获取互斥锁
//        String lockkey ="lock:shop:" + id;
//        Shop shop = null;
//        try {
//            boolean isLock = tryLock(lockkey);
//            //4.2 判断是否获取成功
//            if (!isLock) {
//                //4.3 失败,进入休眠并重试
//                Thread.sleep(50);
//                queryWithMutex(id);
//            }
//            //4.4 不存在则根据id 查询数据库
//            shop = getById(id);
//            //5.不存在,则返回错误
//            if (shop == null)
//            {
//                // 不存在的情况下,写入空值
//                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
//                return null;
//            }
//            //6.查询后,放入redis缓存中
//            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            //7. 释放互斥锁
//            unLock(lockkey);
//        }
//        // 8.返回
//        return shop;
//    }

    public Shop queryWithPassThrough(Long id){
        String key =CACHE_SHOP_KEY + id;
//        1.从redis中查找缓存
        String shopid = stringRedisTemplate.opsForValue().get(key);

        // 2.判断是否存在
        if (StrUtil.isNotBlank(shopid)){
            //3.存在则返回
            Shop shop = JSONUtil.toBean(shopid, Shop.class);
            return shop;
        }

        //判断命中的是否是空值
        if (shopid!= null){
            return null;
        }
        //4. 不存在则根据id 查询数据库
        Shop shop =getById(id);
        //5.不存在,则返回错误
        if (shop == null)
        {
            // 不存在的情况下,写入空值
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //6.查询后,放入redis缓存中
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 7.返回
        return shop;
    }

//    public boolean tryLock(String key){
//        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
//        return BooleanUtil.isTrue(flag);
//    }
//
//    public void unLock(String key){
//        stringRedisTemplate.delete(key);
//    }

    // 设置逻辑过期时间
    public void saveshop2Redis(Long id,Long expireSeconds){
        // 1.查询店铺数据
        Shop shop = getById(id);
        // 2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 3.写入Redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }


    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺id不能为空!");
        }
        //更新数据库
        updateById(shop);
        //
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }
}
